package com.wiscamp.ninechapters.threeparties.mathpix;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class OCRRequest {

    private OCRRequest() {
    }

    /**
     * Send the request with Json parameters to Mathpix API.
     * Parsing the result as a Response object.
     *
     * @param parameters JsonObject to send as the request parameters.
     * @return a Response object.
     * @throws IOException if errors happened during the request execution.
     */
    static OCRResponse getResult(JsonObject parameters) throws IOException {

        var app_id = "max_b_dong_gmail_com";
        var app_key = "2a63c9f954135aeef53b";

        // workaround to resolve #26
        var context = SSLContexts.createSystemDefault();
        var fac = new SSLConnectionSocketFactory(context, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

        // maximum connection waiting time 20 seconds
        var requestConfig = RequestConfig.custom().setConnectTimeout(20000).build();

        // build the HTTP client with above config
        var httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(fac).build();

        // set the request parameters
        var requestParameters = new StringEntity(parameters.toString());

        // API url
        var request = new HttpPost("https://api.mathpix.com/v3/latex");

        // with app_id, app_key, and json type content as the post header
        request.addHeader("app_id", app_id);
        request.addHeader("app_key", app_key);
        request.addHeader("Content-type", "application/json");
        request.setEntity(requestParameters);

        // get the raw result from the execution
        var result = httpClient.execute(request);
        // obtain the message entity of this response
        var json = EntityUtils.toString(result.getEntity(), "UTF-8");

        // return the parsed result
        return new Gson().fromJson(json, OCRResponse.class);

    }
}
